package com.camartsApp.Util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @version .......
 * @创建时间 2025/6/12  下午4:22
 * @创建者 玉苏甫江
 */
@Component
public class JwtUtils {
	private static final String SECRET_KEY = "oK7yP3s9Jv8Lq5TzX2vBcDfGhJkLmNqRs";
	private static final long EXPIRE = 24*60 * 60 * 1000; // 1小时（单位：毫秒）

	/**
	 * 生成JWT Token
	 *
	 * @param userId 用户ID
	 * @param phone 用户手机号
	 * @return JWT字符串
	 */
	public String generateToken(Long userId, String phone) {
		Map<String, Object> claims = new HashMap<>();
		claims.put("userId", userId);
		claims.put("phone", phone);

		Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

		return Jwts.builder()
				.setClaims(claims)
				.setIssuedAt(new Date())
				.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
				.signWith(key, SignatureAlgorithm.HS256)
				.compact();
	}

	/**
	 * 解析Token并返回声明体
	 */
	public Claims getClaimsByToken(String token) {
		if(token.startsWith("Bearer ")) {
			token = token.substring(7);
		}
		try {
			Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
			return Jwts.parserBuilder()
					.setSigningKey(key)
					.build()
					.parseClaimsJws(token)
					.getBody();
		} catch (ExpiredJwtException e) {
			// Token已过期
			return null;
		} catch (Exception e) {
			// 其他异常
			return null;
		}
	}

	/**
	 * 校验Token是否有效
	 */
	public boolean isTokenValid(String token) {
		Claims claims = getClaimsByToken(token);
		return claims != null && claims.getExpiration().after(new Date());
	}

	/**
	 * 获取token中的userId
	 */
	public Long getUserIdFromToken(String token) {
		Claims claims = getClaimsByToken(token);
		if (claims == null) return null;
		Object userIdObj = claims.get("userId");
		if (userIdObj instanceof Integer) {
			return ((Integer) userIdObj).longValue();
		}
		if (userIdObj instanceof Long) {
			return (Long) userIdObj;
		}
		if (userIdObj instanceof String) {
			try {
				return Long.parseLong((String) userIdObj);
			} catch (NumberFormatException e) {
				return null;
			}
		}
		return null;
	}

	/**
	 * 获取token中的phone
	 */
	public String getPhoneFromToken(String token) {
		Claims claims = getClaimsByToken(token);
		if (claims == null) return null;
		return (String) claims.get("phone");
	}
}